package banco;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 
 * @author klebson  lou
 * classe para pegar conexao com o banco
 */
public class DB {
	private static DB instance = null;
	private Connection connection = null;
	private int client = 0;
	
	private DB(){
		try{			
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager.getConnection("jdbc:mysql://localhost/usuario","root","root");
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	//singleton para conexao com banco	
	public static DB getInstance(){
		if(instance==null){
			instance=new DB();
		}
		return instance;
	}	
	public static Connection getConnections(){
		Connection con = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection("jdbc:mysql://localhost/usuario","root","root");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	    return con;
	}
	public Connection getConnection(){
		if(connection==null){
		throw new RuntimeException("connetion==null");	
		}
		client++;
		return connection;
	}
	//fecha conexao com banco
	public void fecharBanco(){
		client--;
		if(client>0){
			return;
		}
		try{
			connection.close();
			instance=null;
			connection =null;			
			
		}catch (Exception e) {
			e.printStackTrace();
		}
		}
	}


